<template>
  <div class="animal-detail">
    <!-- 返回导航 -->
    <div class="nav-bar">
      <el-page-header @back="$router.back()">
        <template #content>
          <span class="page-title">动物详情</span>
        </template>
      </el-page-header>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="8" animated />
    </div>

    <!-- 错误状态 -->
    <div v-else-if="error" class="error-container">
      <el-empty description="加载失败，请重试">
        <el-button type="primary" @click="loadAnimalDetail">重新加载</el-button>
      </el-empty>
    </div>

    <!-- 数据为空 -->
    <div v-else-if="!animal" class="empty-container">
      <el-empty description="暂无数据" />
    </div>

    <!-- 正常显示 -->
    <div v-else>

    <el-card class="detail-card" shadow="hover">
      <el-row :gutter="30" class="top-info">
      <el-col :span="8">
          <div class="image-wrapper">
            <img 
              v-if="animal.photo"
              :src="animal.photo" 
              :alt="animal.name"
              class="animal-img"
              @error="handleImageError"
            />
            <div v-else class="no-image-placeholder">
              <el-icon :size="60"><Picture /></el-icon>
              <p>暂无图片</p>
            </div>
            <div class="status-badge">
              <el-tag 
                :type="getStatusType(animal.status)" 
                size="large"
                effect="dark"
              >
                {{ getStatusText(animal.status) }}
              </el-tag>
            </div>
          </div>
      </el-col>
      <el-col :span="16">
          <div class="animal-info">
            <h2 class="animal-name">
              <el-icon><Star /></el-icon>
              {{ animal.name || "未命名" }}
            </h2>
            <div class="info-grid">
              <div class="info-item">
                <el-icon class="info-icon"><Files /></el-icon>
                <div class="info-content">
                  <span class="info-label">种类</span>
                  <span class="info-value">{{ animal.species || '未知' }}</span>
                </div>
              </div>
              <div class="info-item">
                <el-icon class="info-icon"><User /></el-icon>
                <div class="info-content">
                  <span class="info-label">性别</span>
                  <span class="info-value">{{ animal.gender || '未知' }}</span>
                </div>
              </div>
              <div class="info-item">
                <el-icon class="info-icon"><Brush /></el-icon>
                <div class="info-content">
                  <span class="info-label">毛色</span>
                  <span class="info-value">{{ animal.color || '未知' }}</span>
                </div>
              </div>
              <div class="info-item">
                <el-icon class="info-icon"><Timer /></el-icon>
                <div class="info-content">
                  <span class="info-label">年龄</span>
                  <span class="info-value">{{ animal.age || '未知' }}</span>
                </div>
              </div>
              <div class="info-item">
                <el-icon class="info-icon"><Calendar /></el-icon>
                <div class="info-content">
                  <span class="info-label">救助时间</span>
                  <span class="info-value">{{ formatTime(animal.rescueTime) }}</span>
                </div>
              </div>
              <div class="info-item">
                <el-icon class="info-icon"><Location /></el-icon>
                <div class="info-content">
                  <span class="info-label">发现地点</span>
                  <span class="info-value">{{ animal.location || '未知' }}</span>
                </div>
              </div>
              <div class="info-item">
                <el-icon class="info-icon"><Tickets /></el-icon>
                <div class="info-content">
                  <span class="info-label">档案编号</span>
                  <span class="info-value">#{{ animal.id || '未知' }}</span>
                </div>
              </div>
              <div class="info-item">
                <el-icon class="info-icon"><Collection /></el-icon>
                <div class="info-content">
                  <span class="info-label">品种</span>
                  <span class="info-value">{{ animal.breed || '未知' }}</span>
                </div>
              </div>
              <div class="info-item">
                <el-icon class="info-icon"><Document /></el-icon>
                <div class="info-content">
                  <span class="info-label">档案创建时间</span>
                  <span class="info-value">{{ formatTime(animal.createTime) }}</span>
                </div>
              </div>
            </div>
            <!-- 状态提示 -->
            <div v-if="animal.status === 2" class="status-notice">
              <el-alert
                title="审核中"
                type="warning"
                :closable="false"
                show-icon
              >
                <template #default>
                  <p>该动物的领养申请正在审核中，请耐心等待审核结果。</p>
                </template>
              </el-alert>
            </div>
            <div v-else-if="animal.status === 1" class="status-notice">
              <el-alert
                title="已被领养"
                type="success"
                :closable="false"
                show-icon
              >
                <template #default>
                  <p>该动物已被成功领养，感谢您的关注。</p>
                </template>
              </el-alert>
            </div>

            <div class="action-buttons">
              <el-button 
                v-if="animal.status === 0"
                type="success" 
                size="large" 
                @click="goAdopt"
              >
                <el-icon><Check /></el-icon>
                申请领养
              </el-button>
              <el-button 
                v-else-if="animal.status === 2"
                type="warning" 
                size="large"
                disabled
              >
                <el-icon><Clock /></el-icon>
                审核中
              </el-button>
              <el-button 
                v-else-if="animal.status === 1"
                type="info" 
                size="large"
                disabled
              >
                <el-icon><SuccessFilled /></el-icon>
                已领养
              </el-button>
              <el-button 
                v-else
                type="info" 
                size="large"
                disabled
              >
                <el-icon><InfoFilled /></el-icon>
                暂不可领养
              </el-button>
              <el-button size="large" @click="handleConsult">
                <el-icon><ChatDotRound /></el-icon>
                咨询详情
              </el-button>
            </div>
          </div>
      </el-col>
    </el-row>
    </el-card>

    <!-- 详细信息 -->
    <el-card class="detail-card" shadow="hover">
      <el-tabs v-model="activeTab" type="card" class="detail-tabs">
      <el-tab-pane label="基本信息" name="info">
          <div class="tab-content">
            <div class="description">
              <h3>
                <el-icon><InfoFilled /></el-icon>
                详细描述
              </h3>
              <p>{{ animal.description || '暂无详细描述' }}</p>
            </div>
          </div>
      </el-tab-pane>

      <el-tab-pane label="健康档案" name="health">
          <div class="tab-content">
            <el-table :data="healthRecords" border stripe v-if="healthRecords.length > 0">
              <el-table-column prop="checkDate" label="检查日期" width="180" />
          <el-table-column prop="disease" label="疾病记录" />
          <el-table-column prop="vaccine" label="疫苗情况" />
          <el-table-column prop="notes" label="备注" />
        </el-table>
            <el-empty v-else description="暂无健康档案" :image-size="150" />
          </div>
      </el-tab-pane>

      <el-tab-pane label="救助故事" name="story">
          <div class="tab-content">
            <div v-if="story" class="story-content">
              <h3>
                <el-icon><Document /></el-icon>
                {{ story.title }}
              </h3>
              <div class="story-text">
          <p>{{ story.content }}</p>
        </div>
              <!-- 故事图片展示 -->
              <div v-if="storyPhotos.length > 0" class="story-images">
                <h4 class="images-title">
                  <el-icon><Picture /></el-icon>
                  相关图片 ({{ storyPhotos.length }})
                </h4>
                <div class="images-grid">
                  <div 
                    v-for="(photo, index) in storyPhotos" 
                    :key="index"
                    class="image-item"
                    @click="previewStoryImage(index)"
                  >
                    <img 
                      :src="formatImageUrl(photo)" 
                      :alt="`故事图片${index + 1}`"
                      @error="handleImageError"
                    />
                    <div class="image-overlay">
                      <el-icon><ZoomIn /></el-icon>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <el-empty v-else description="暂无故事信息" :image-size="150" />
          </div>
      </el-tab-pane>
    </el-tabs>
    </el-card>
    </div>

    <!-- 图片预览对话框 -->
    <el-dialog
      v-model="previewImageVisible"
      :show-close="true"
      :close-on-click-modal="true"
      width="98%"
      top="2vh"
      class="preview-dialog"
      @close="previewImageVisible = false"
    >
      <div class="preview-container">
        <el-carousel
          :initial-index="previewIndex"
          :height="'90vh'"
          indicator-position="outside"
          @change="(index) => previewIndex = index"
        >
          <el-carousel-item v-for="(url, index) in previewImageList" :key="index">
            <div class="carousel-image-container">
              <img 
                :src="url" 
                :alt="`图片${index + 1}`"
                class="preview-image-full"
                @error="handleImageError"
              />
            </div>
          </el-carousel-item>
        </el-carousel>
        <div class="preview-info">
          <span>{{ previewIndex + 1 }} / {{ previewImageList.length }}</span>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from "axios";
import { ElMessage } from "element-plus";
import { 
  Star, Files, User, Brush, Calendar, Check, ChatDotRound, 
  InfoFilled, Document, Timer, Location, Clock, SuccessFilled,
  Tickets, Collection, Picture, ZoomIn
} from '@element-plus/icons-vue';

export default {
  components: {
    Star,
    Files,
    User,
    Brush,
    Calendar,
    Check,
    ChatDotRound,
    InfoFilled,
    Document,
    Timer,
    Location,
    Clock,
    SuccessFilled,
    Tickets,
    Collection,
    Picture,
    ZoomIn
  },
  data() {
    return {
      animal: null,
      healthRecords: [],
      story: null,
      activeTab: "info",
      loading: false,
      error: false,
      previewImageVisible: false,
      previewImageList: [],
      previewIndex: 0,
    };
  },
  computed: {
    storyPhotos() {
      if (!this.story || !this.story.photo) {
        return [];
      }
      // 如果 photo 是字符串，可能是逗号分隔的多个图片
      if (typeof this.story.photo === 'string') {
        return this.story.photo.split(',').map(url => url.trim()).filter(url => url);
      }
      // 如果 photo 是数组
      if (Array.isArray(this.story.photo)) {
        return this.story.photo;
      }
      return [];
    },
  },
  async mounted() {
    await this.loadAnimalDetail();
  },
  watch: {
    '$route.params.id'(newId, oldId) {
      // 当路由参数ID改变时重新加载数据
      if (newId && newId !== oldId) {
        this.loadAnimalDetail();
      }
    },
    '$route.query.refresh'() {
      // 当有refresh参数时刷新数据
      if (this.$route.query.refresh) {
        this.loadAnimalDetail();
      }
    }
  },
  methods: {
    async loadAnimalDetail() {
    const id = this.$route.params.id;
      if (!id) {
        this.error = true;
        ElMessage.error('缺少动物ID参数');
        return;
      }

      this.loading = true;
      this.error = false;

      try {
    const res = await axios.get(`http://localhost:8080/api/animal/detail/${id}`);
    if (res.data.code === 200) {
          this.animal = res.data.data?.animal || res.data.data;
          this.healthRecords = res.data.data?.health || [];
          this.story = res.data.data?.story;
          
          // 如果后端返回的数据结构不同，尝试适配
          if (!this.animal && res.data.data) {
            this.animal = res.data.data;
    }
        } else {
          this.error = true;
          ElMessage.error(res.data.msg || '加载动物信息失败');
        }
      } catch (error) {
        this.error = true;
        console.error('加载动物详情失败:', error);
        ElMessage.error(error.response?.data?.msg || '加载动物信息失败，请检查网络连接');
      } finally {
        this.loading = false;
      }
    },
    handleImageError(event) {
      // 图片加载失败时显示占位图
      event.target.src = '';
    },
    getStatusText(status) {
      // 根据后端：0待领养 1已领养 2审核中
      const statusTexts = ["待领养", "已领养", "审核中"];
      return statusTexts[status] || '未知';
    },
    getStatusType(status) {
      // 0:待领养(success), 1:已领养(info), 2:审核中(warning)
      const types = ['success', 'info', 'warning'];
      return types[status] || 'info';
    },
    formatTime(time) {
      if (!time) return '未知';
      
      if (typeof time === 'string') {
        const date = new Date(time);
        if (isNaN(date.getTime())) {
          return time;
        }
        time = date;
      }
      
      if (time instanceof Date) {
        const year = time.getFullYear();
        const month = String(time.getMonth() + 1).padStart(2, '0');
        const day = String(time.getDate()).padStart(2, '0');
        const hours = String(time.getHours()).padStart(2, '0');
        const minutes = String(time.getMinutes()).padStart(2, '0');
        return `${year}-${month}-${day} ${hours}:${minutes}`;
      }
      
      return time;
    },
    goAdopt() {
      // 只有待领养状态(status=0)才能申请
      if (this.animal.status === 0) {
      this.$router.push(`/user/adoptForm/${this.animal.id}`);
      } else {
        ElMessage.warning('该动物当前状态不可申请领养');
      }
    },
    handleConsult() {
      ElMessage.info('咨询功能开发中，请联系管理员');
    },
    formatImageUrl(url) {
      if (!url) return '';
      if (url.startsWith('http://') || url.startsWith('https://')) {
        return url;
      }
      return `http://localhost:8080${url.startsWith('/') ? url : '/' + url}`;
    },
    previewStoryImage(index) {
      this.previewImageList = this.storyPhotos.map(photo => this.formatImageUrl(photo));
      this.previewIndex = index;
      this.previewImageVisible = true;
    },
  },
};
</script>

<style scoped>
.animal-detail {
  padding: 20px;
  background: #f5f7fa;
  min-height: 100%;
}

.loading-container,
.error-container,
.empty-container {
  padding: 40px 20px;
  background: #fff;
  border-radius: 12px;
  margin-bottom: 20px;
}

.loading-container {
  padding: 40px;
}

.nav-bar {
  margin-bottom: 20px;
}

.page-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.detail-card {
  margin-bottom: 20px;
  border-radius: 12px;
  overflow: hidden;
}

.detail-card:last-child {
  margin-bottom: 0;
}

.top-info {
  padding: 10px 0;
}

.image-wrapper {
  position: relative;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.animal-img {
  width: 100%;
  height: auto;
  display: block;
  border-radius: 12px;
  object-fit: cover;
}

.no-image-placeholder {
  width: 100%;
  min-height: 300px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: #f5f7fa;
  border-radius: 12px;
  color: #909399;
}

.no-image-placeholder p {
  margin-top: 12px;
  font-size: 14px;
}

.status-badge {
  position: absolute;
  top: 16px;
  right: 16px;
}

.animal-info {
  padding-left: 20px;
}

.animal-name {
  display: flex;
  align-items: center;
  gap: 12px;
  margin: 0 0 24px 0;
  font-size: 28px;
  font-weight: 600;
  color: #303133;
}

.animal-name .el-icon {
  font-size: 32px;
  color: #f39c12;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
  margin-bottom: 24px;
}

/* 状态提示 */
.status-notice {
  margin-bottom: 20px;
}

.status-notice :deep(.el-alert) {
  border-radius: 8px;
}

.status-notice :deep(.el-alert__content) {
  padding-left: 8px;
}

.status-notice p {
  margin: 0;
  font-size: 14px;
  line-height: 1.6;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 16px;
  background: #fafafa;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.info-item:hover {
  background: #f0f9ff;
  transform: translateY(-2px);
}

.info-icon {
  font-size: 24px;
  color: #409eff;
  flex-shrink: 0;
}

.info-content {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.info-label {
  font-size: 12px;
  color: #909399;
}

.info-value {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.action-buttons {
  display: flex;
  gap: 12px;
}

.action-buttons .el-button {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  font-weight: 500;
}

/* 标签页样式 */
.detail-tabs {
  margin-top: 0;
}

:deep(.el-tabs__header) {
  margin-bottom: 24px;
}

:deep(.el-tabs__item) {
  font-size: 15px;
  font-weight: 500;
}

/* Tab 内容 */
.tab-content {
  padding: 20px 0;
}

.description h3,
.story-content h3 {
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 0 0 16px 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.description h3 .el-icon,
.story-content h3 .el-icon {
  font-size: 20px;
  color: #409eff;
}

.description p,
.story-text p {
  font-size: 15px;
  line-height: 1.8;
  color: #606266;
  text-align: justify;
}

.story-text {
  background: #fafafa;
  padding: 20px;
  border-radius: 8px;
  border-left: 4px solid #409eff;
  margin-bottom: 24px;
}

/* 故事图片展示 */
.story-images {
  margin-top: 24px;
}

.images-title {
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 0 0 16px 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.images-title .el-icon {
  font-size: 18px;
  color: #409eff;
}

.images-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 16px;
}

.image-item {
  position: relative;
  width: 100%;
  aspect-ratio: 1;
  border-radius: 8px;
  overflow: hidden;
  cursor: pointer;
  background: #f5f7fa;
  transition: all 0.3s ease;
}

.image-item:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.15);
}

.image-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  display: block;
}

.image-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.4);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.image-item:hover .image-overlay {
  opacity: 1;
}

.image-overlay .el-icon {
  font-size: 32px;
  color: #fff;
}

/* 图片预览对话框 */
.preview-dialog :deep(.el-dialog__body) {
  padding: 10px;
}

.preview-container {
  position: relative;
  min-height: 90vh;
}

.carousel-image-container {
  width: 100%;
  height: 90vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #000;
  padding: 10px;
}

.preview-image-full {
  max-width: 98%;
  max-height: 98%;
  object-fit: contain;
  display: block;
}

.preview-info {
  position: absolute;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  background: rgba(0, 0, 0, 0.6);
  color: #fff;
  padding: 8px 16px;
  border-radius: 20px;
  font-size: 14px;
  z-index: 10;
}

/* 表格样式优化 */
:deep(.el-table) {
  border-radius: 8px;
}

:deep(.el-table__header) {
  background: #fafafa;
}

:deep(.el-table__header th) {
  background: #fafafa;
  font-weight: 600;
  color: #303133;
}

/* 空状态 */
:deep(.el-empty) {
  padding: 40px 0;
}

/* 响应式 */
@media (max-width: 768px) {
  .animal-detail {
    padding: 10px;
  }
  
  .top-info {
    flex-direction: column;
  }
  
  .animal-info {
    padding-left: 0;
    margin-top: 20px;
  }
  
  .info-grid {
    grid-template-columns: repeat(2, 1fr);
    gap: 12px;
  }
  
  .action-buttons {
    flex-direction: column;
  }
  
  .detail-card {
    padding: 0;
  }
}
</style>
